const categoryService = {
  //Define the basic content that should display for "Category".
  categoryQueryRequest : {
    originCollection : "Category",
    fromCollectionsLookUpParmas : [
                                    {
                                    name : "ICON",
                                    let : {
                                      iconID : '$iconID'
                                    },
                                    pipeline : [
                                      {
                                        operator : 'eq',
                                        fieldName : '$iconID',
                                        definedName : '$$iconID'
                                      },                                 
                                    ],
                                    project : {
                                      _id: 0,
                                      iconID: 1,
                                      desc: 1,
                                      // base64: 1
                                    },
                                    as : 'Category2IconID',
                                  }
    ],
    matchCondition : {
      matchFieldName : 'categoryID',
      operator : 'lte',
      value : 8
    },
    limit : 8
  },

  defautlIconListQueryRequest : {
    originCollection : "ICON",
    matchCondition : {
      matchFieldName : 'iconID',
      operator : 'lte',
      value : 8
    },
    limit : 8
  },

  aggregatedCategory() {
    return wx.cloud.callFunction({
      name : "AggregatedLookUpQuery",
      data : {
        queryRequest : this.categoryQueryRequest
      }
    })
    .then(res => {
      let categoryList = res.result;
      return this.resolveIconBase64InLocalStorage(categoryList);
    });
  },

  /* Save the icon base64 into Local Storage, then could retrieve the base64 from Local Storage instead of Clould at all.*/
  async resolveIconBase64InLocalStorage(categoryList) {
    try {
      let count = 0;

      categoryList.every(category => {
        let category2IconIDObj = category.Category2IconID[0];
        let targetBase64 = wx.getStorageSync(category.Category2IconID[0].desc);
        if(!targetBase64) {
          console.log(`Missing the target base64 for '${category2IconIDObj.desc}' icon, turn to retrieve all the icon info for category list!`);
          return false;
        }
        else{
          category2IconIDObj.base64 = targetBase64;
          count++;

          return true;
        }
      });

      /*
        If there is some base64 of the icon is missing, 
        re-load the base64 of category icon from Cloud Base, then cache into the Local Storage.
      */
      if(count != categoryList.length) {
         await wx.cloud.callFunction({
          name : "SingleCollectionQuery",
          data : {
            queryRequest : this.defautlIconListQueryRequest
          }
        })
        .then(res => {
          let iconList = res.result;
          console.log(`Interrupt the icon base64 retrieval in 'Local Storage' at count : ${count}, retrieve the icon list from 'categoryService.resolveIconBase64InLocalStorage' : ${iconList}`);

          categoryList.forEach((category, index)=> {
            let targetDesc = category.Category2IconID[0].desc;
            category.Category2IconID[0].base64 = iconList[index].base64;

            let targetBase64 = category.Category2IconID[0].base64;
            if(targetBase64) {
              wx.setStorageSync(targetDesc, targetBase64);
            }
           });

           console.log(`Succeed to re-load the icon base64 in 'ICON' ${this.defautlIconListQueryRequest.originCollection}...`);
        });
      }

      return categoryList;
    } catch (e) {
      console.log(`When handle the base64 for each icon of category list, there is exception : ${e}`);
    }
  },
}

export {categoryService};